<?php

class Admin_UserController extends Zend_Controller_Action {

    // Mang tham so nhan duoc o moi Action
    protected $_arrParam;
    protected $_page = 1;
    // Duong dan cua Action chinh
    protected $_actionMain;

    public function init() {
        // Mang tham so nhan duoc o moi Action
        $this->_arrParam = $this->_request->getParams();

        //check permissions
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $group_id = $identity->group;
        $groupsModel = new Admin_Model_Groups();
        $group_info = $groupsModel->fetchRow('id=' . $group_id)->toArray();
        $permissions = unserialize($group_info['permissions']);
        if (!$group_info['admin'] || (!in_array($this->_arrParam ['action'], $permissions[ucfirst($this->_arrParam ['controller'])])&& $this->_arrParam ['action'] !='index')) {
            $this->_redirect('access_denied');
            die();
        }

        $this->_page = $this->_arrParam ['page'];
        if ($this->_page == '' || $this->_page <= 0) {
            $this->_page = 1;
        }

        // Duong dan cua Action chinh
        $this->_actionMain = '/' . $this->_arrParam ['module'] .
                '/' . $this->_arrParam ['controller'] . '/dashboard/page/' . $this->_page;
    }

    /**
     * function Index
     */
    public function indexAction(){
        $this->_redirect($this->_actionMain);
    }
    
    /**
     * main of users controller
     */
    public function dashboardAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_USER_INDEX");
        $this->view->headTitle($this->view->title);
        $modelUser = new User_Model_Accounts ();
        $listUser = $modelUser->fetchUser();
        $paginator = Zend_Paginator::factory($listUser);
        $paginator->setItemCountPerPage(NUM_PER_PAGE);
        $paginator->setCurrentPageNumber($this->_page);
        $this->view->page = $this->_page;
        $this->view->paginator = $paginator;
    }

    /**
     * function delete multi users (ajax)
     */
    public function deleteitemsAction() {
        $this->_helper->layout()->disableLayout();

        $accountModel = new Admin_Model_Accounts ();

        if ($this->_request->isPost()) {

            $item = $this->_arrParam ['cid'];

            foreach ($item as $k => $v) {

                $accountModel->deleteUser($v);
            }
        }

        $this->_redirect($this->_actionMain);
    }

    /**
     * function change status of use (ajax)
     */
    public function activeAction() {
        $this->_helper->layout()->disableLayout();
        $type = $this->_request->getParam('type', 1);
        $id = $this->_request->getParam('id', 0);

        if ($type > 0) {
            $type = 1;
        } else {
            $type = 0;
        }

        $modelMenu = new Admin_Model_Accounts ();
        $modelMenu->update(array(
            'active' => $type
                ), 'id=' . $id);

        $this->_redirect($this->_actionMain);
    }

    /**
     * function insert one user
     */
    public function insertAction() {
        $messages = array();
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_USER_INSERT");
        $this->view->headTitle($this->view->title);

        //get tat cac cac group
        $groupsModel = new Admin_Model_Groups ();
        $listGroups = $groupsModel->fetchGroup(array(
            'active' => 1
        ));
        $listGroups = $listGroups->toArray();

        //top cac option de add vao forms
        $options = array();
        foreach ($listGroups as $key => $value) {

            $options [$value ['id']] = $value ['name'];
        }

        //get form va add cac option vao form
        $form = new Admin_Form_Users_InsertUser ();
        $groups = $form->getElement('group');
        $groups->addMultiOptions($options);
        $groups->setValue(0);
        $back = $form->getElement('back');
        $back->setAttrib('onclick', "window.location='" . $this->getFrontController()->getBaseUrl() . "/admin/user/dashboard/page/" . $this->_page . "';");

        //kiem tra co phai la post khong
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
                $userModel = new Admin_Model_Accounts();

                //kiem tra user da ton tai chua
                $checkUsername = $userModel->fetchUser(array(
                    'username' => trim($form->getValue('username'))
                ));

                $checkEmail = $userModel->fetchUser(array(
                    'email' => trim($form->getValue('email'))
                ));

                if (count($checkUsername) > 0 || count($checkEmail) > 0) {
                    if (count($checkEmail) > 0) {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_VALIDATOR_EMAIL_USED"),
                            'type' => 'errormsg'
                        );
                    }

                    if (count($checkUsername) > 0) {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_VALIDATOR_USERNAME_USED"),
                            'type' => 'errormsg'
                        );
                    }
                } else {

                    $status = $_POST ['active'];
                    $username = strtolower(trim($form->getValue('username')));

                    $user_info = array(
                        'username' => $username,
                        'password' => md5($form->getValue('password')),
                        'email' => trim($form->getValue('email')),
                        'gender' => $this->getRequest()->getPost('gender'),
                        'active' => $status,
                        'group' => $this->getRequest()->getPost('group')
                    );

                    $accountId = $userModel->insert($user_info);

                    $messages [] = array(
                        'text' => $translate->_("TEXT_NOTE_INSERT_USERT_SUCCESS"),
                        'type' => 'success'
                    );
                }
            }
        }

        $this->view->message = $messages;
        $this->view->form = $form;
    }

    /**
     * function edit info one user by id
     */
    public function updateAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_USER_UPDATE");
        $this->view->headTitle($this->view->title);

        $groupsModel = new Admin_Model_Groups ();
        $listGroups = $groupsModel->fetchGroup(array(
            'active' => 1
        ));
        $listGroups = $listGroups->toArray();

        $options = array();
        foreach ($listGroups as $key => $value) {
            $options [$value ['id']] = $value ['name'];
        }

        $form = new Admin_Form_Users_UpdateUser ();
        $groups = $form->getElement('group');
        $groups->addMultiOptions($options);
        $groups->setValue(0);
        $back = $form->getElement('back');
        $back->setAttrib('onclick', "window.location='" . $this->getFrontController()->getBaseUrl() . "/admin/user/dashboard/page/" . $this->_page . "';");

        $id_user = $this->_getParam('id', 0);
        $userModel = new Admin_Model_Accounts ();
        $messages = array();

        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
                $email = trim($form->getValue('email'));
                $email = strtolower($email);
                $username = strtolower($form->getValue('username'));
                $checkUsername = $userModel->fetchRow('username ="' . $username . '" and id!=' . $id_user);
                $checkEmail = $userModel->fetchRow('email ="' . $email . '" and id!=' . $id_user);
                if (count($checkUsername) > 0 || count($checkEmail) > 0) {
                    if (count($checkEmail) > 0) {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_VALIDATOR_EMAIL_USED"),
                            'type' => 'errormsg'
                        );
                    }

                    if (count($checkUsername) > 0) {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_VALIDATOR_USERNAME_USED"),
                            'type' => 'errormsg'
                        );
                    }
                } else {

                    $status = $_POST ['active'];
                    $processUser = $userModel->updateUser($id_user, $username, $form->getValue('password'), $email, $this->getRequest()->getPost('gender'), $status, $this->getRequest()->getPost('group'));
                    if ($processUser) {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_NOTE_INSERT_UPDATE_SUCCESS"),
                            'type' => 'success'
                        );
                    } else {
                        $messages [] = array(
                            'text' => $translate->_("TEXT_NOTE_INSERT_UPDATE_FAILD"),
                            'type' => 'errormsg'
                        );
                    }
                }
            }
        } else {
            $data = $userModel->fetchRow('id=' . $id_user);
            $data = $data->toArray();
            if (count($data) > 0) {
                $form->populate($data);
            } else {
                $this->_redirect($this->_actionMain);
            }
        }

        $this->view->message = $messages;
        $this->view->form = $form;
    }

    /**
     * function delete one user by id
     */
    public function deleteAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_USER_DELETE");
        $this->view->headTitle($this->view->title);

        $id = $this->_getParam('id', 0);
        $userModel = new Admin_Model_Accounts ();
        if ($this->getRequest()->isPost()) {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Yes') {
                $process = $userModel->deleteUser($id);
            }

            $this->_redirect($this->_actionMain);
        } else {
            $data = $userModel->fetchRow('id=' . $id);
            $this->view->user = $data->toArray();
        }
    }

}